// 保存设置到Chrome存储
function saveOptions() {
    const settings = {
        defaultTargetLanguage: document.getElementById('default-target-language').value,
        translationService: document.getElementById('translation-service').value,
        googleApiKey: document.getElementById('google-api-key').value,
        baiduAppId: document.getElementById('baidu-app-id').value,
        baiduApiKey: document.getElementById('baidu-api-key').value
    };

    chrome.storage.sync.set(settings, () => {
        const status = document.getElementById('status');
        status.textContent = '设置已保存';
        status.className = 'status success';
        setTimeout(() => {
            status.textContent = '';
            status.className = 'status';
        }, 2000);
    });
}

// 从Chrome存储加载设置
function loadOptions() {
    chrome.storage.sync.get({
        defaultTargetLanguage: 'zh',
        translationService: 'libre',
        googleApiKey: '',
        baiduAppId: '',
        baiduApiKey: ''
    }, (items) => {
        document.getElementById('default-target-language').value = items.defaultTargetLanguage;
        document.getElementById('translation-service').value = items.translationService;
        document.getElementById('google-api-key').value = items.googleApiKey;
        document.getElementById('baidu-app-id').value = items.baiduAppId;
        document.getElementById('baidu-api-key').value = items.baiduApiKey;
        
        // 根据选择的翻译服务显示/隐藏API设置
        updateApiKeyInputs(items.translationService);
    });
}

// 根据选择的翻译服务显示/隐藏API设置
function updateApiKeyInputs(service) {
    const googleApiKeyGroup = document.getElementById('google-api-key-group');
    const baiduApiKeyGroup = document.getElementById('baidu-api-key-group');

    googleApiKeyGroup.style.display = service === 'google' ? 'block' : 'none';
    baiduApiKeyGroup.style.display = service === 'baidu' ? 'block' : 'none';
}

// 事件监听器
document.addEventListener('DOMContentLoaded', () => {
    loadOptions();
    
    // 保存按钮点击事件
    document.getElementById('save-settings').addEventListener('click', saveOptions);
    
    // 翻译服务选择变化事件
    document.getElementById('translation-service').addEventListener('change', (e) => {
        updateApiKeyInputs(e.target.value);
    });
});
